from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.urls import reverse
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView

# 导入加密库
import hashlib

# 导入图片库
# 绘画库
from PIL import ImageDraw

# 字体库
from PIL import ImageFont

# 图片库
from PIL import Image

# 随机库
import random

# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango import settings
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

# 导入序列化类
from myapp.myser import UserSer


# 导入中间件
from django.utils.deprecation import MiddlewareMixin


# 声明自定义中间件
class MyMiddleware(MiddlewareMixin):
    # 请求之前
    def process_request(self, request):
        print('请求之前')

    # 模板渲染之前
    def process_view(self, request, view_func, view_args, view_kwargs):
        print('模板渲染之前')
        pass

    # 异常发生时
    def process_exception(self, request, exception):
        # 捕获异常
        if isinstance(exception, ValueError):
            return HttpResponse('404')

    # 请求之后
    def process_response(self, request, response):
        print('请求之后')
        return response


# 序列化操作(基于json)
def json_test(request):
    # 查询数据集
    res = User.objects.all()
    # 进行序列化操作
    mylist = json.loads(serialize('json', res, ensure_ascii=False))
    # 返回json对象
    return JsonResponse(mylist, safe=False, json_dumps_params={'ensure_ascii': False})


# 序列化操作(基于drf)
class JsonDrf(APIView):
    def get(self, request):
        # 查询数据
        users = User.objects.all()
        # 序列化操作
        user_ser = UserSer(users, many=True)
        # 返回json
        return Response(user_ser.data)


# 首页展示
def index(request):
    # title = 'Hello Django'
    # num = 100
    # li = [1, 2, 3, 4, 5]
    # dic = {'name': 'zhangsan', 'age': 18}
    if request.method == 'GET':
        user_list = User.objects.all()  # 取出表中所有数据
        return render(request, 'index.html', locals())

    if request.method == 'POST':
        # 搜索
        username = request.POST.get('username')
        if username:
            user_list = User.objects.filter(username__contains=username)
            return render(request, 'index.html', locals())
    user_list = User.objects.all()
    return render(request, 'index.html', locals())


# 增加
def create(request):
    if request.method == 'POST':
        user = request.POST['user']
        pwd = request.POST['pwd']
        img = request.FILES.get('img')
        file = os.path.join(settings.UPLOAD_ROOT, img.name)
        f = open(file, 'wb')
        for i in img.chunks():
            f.write(i)
        f.close()
        User.objects.create(username=user, password=pwd, img=img)
        return redirect(reverse('index'))
    return render(request, 'create.html', locals())


# 删除
def delete(request):
    if request.method == 'GET':
        id = request.GET.get('id')
        User.objects.filter(id=id).delete()
        return redirect(reverse('index'))
    return redirect(reverse('index'))


# 修改
def change(request):
    if request.method == 'GET':
        id = request.GET.get('id')
        user = User.objects.filter(id=id).first()
        print(id)
        return render(request, 'change.html', locals())
    if request.method == 'POST':
        id = request.POST.get('id')
        user = request.POST['user']
        pwd = request.POST['pwd']
        img = request.FILES.get('img')
        file = os.path.join(settings.UPLOAD_ROOT, img.name)
        f = open(file, 'wb')
        for i in img.chunks():
            f.write(i)
        f.close()
        User.objects.filter(id=id).update(username=user, password=pwd, img='static/upload/'+img.name)
        return redirect(reverse('index'))
    return render(request, 'change.html')


class MyView(View):
    def get(self, request):
        return HttpResponse('这里是get')

    def post(self, request):
        return HttpResponse('这里是post')
